package chapter05;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "lastAccessSerlet", urlPatterns = "/lastAccessSerlet")
public class lastAccessSerlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        Cookie[] cookies=req.getCookies();
        boolean flag=false;
        if (cookies.length >0&&cookies!=null) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("lastTime".equals(name)) {
                    flag = true;
                    String value = cookie.getValue();
                    value = URLDecoder.decode(value, "utf-8");
                    resp.getWriter().write("欢迎回来，您上次访问的时间为：" + value);
                    String str_time = getCurrentData();
                    cookie.setValue(str_time);
                    cookie.setMaxAge(60 * 60 * 24 * 30);
                    resp.addCookie(cookie);
                    break;
                }
            }
        }
        if (cookies==null || cookies.length==0 || flag==false){
            String str_data = getCurrentData();
            Cookie cookie=new Cookie("lastTime",str_data);
                cookie.setMaxAge(60*60*24*30);
                resp.addCookie(cookie);
                resp.getWriter().write("您好，欢迎您首次访问");
        }
    }

    private String getCurrentData() throws UnsupportedEncodingException {
        Date data = new Date();
        SimpleDateFormat timesdf = new SimpleDateFormat("yyyyy年MM月dd日 HH:mm:ss");
        String str_time =timesdf.format(data);
        str_time = URLEncoder.encode(str_time, "utf-8");
        return str_time;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}

